package com.haoc.a520demo;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.haoc.a520demo.utils.Myutils;
import com.huawei.agconnect.applinking.AGConnectAppLinking;
import com.huawei.agconnect.auth.AGConnectAuth;
import com.huawei.agconnect.cloud.storage.core.AGCStorageManagement;
import com.huawei.agconnect.cloud.storage.core.StorageReference;
import com.huawei.agconnect.cloud.storage.core.UploadTask;
import com.huawei.agconnect.remoteconfig.AGConnectConfig;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

import java.io.File;


public class MainActivity extends Activity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    private AGConnectConfig config;
    private static AGCStorageManagement mAGCStorageManagement;
    private final String flag = "purple";
    private ImageView img_banner;
    private ImageView img_add;
    private ImageView img_share;
    private static String App_LinkingUrl = "https://520.drcn.agconnect.link/E4lv";
    private static final int LOCAL_CROP = 13;// 本地图库
    private String[] permissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        login();
        // 获取远程配置对象实例
        config = AGConnectConfig.getInstance();
        // 远程配置定制主题
        setTheme();
        // 设置状态栏效果
        Myutils.setStatusBar(MainActivity.this);
        // 申请权限
        ActivityCompat.requestPermissions(this, permissions, 1);
    }

    private void init() {
        img_banner = findViewById(R.id.img_banner);
        img_add = findViewById(R.id.img_add);
        img_share = findViewById(R.id.img_share);
        img_banner.setOnClickListener(this);
        img_add.setOnClickListener(this);
        img_share.setOnClickListener(this);
        AGConnectAppLinking.getInstance().getAppLinking(this).addOnSuccessListener(resolvedLinkData -> {
            Uri deepLink = null;
            if (resolvedLinkData != null) {
                deepLink = resolvedLinkData.getDeepLink();
            }
            //根据Deep Link信息来进行后续处理，比如打开详情页面或配置页面等。
            if (deepLink != null) {
                Intent intent = new Intent(MainActivity.this, PhotoActivity.class);
                intent.putExtra("Url", deepLink.toString());
                startActivity(intent);
            }
        }).addOnFailureListener(
                e -> {
                    Log.w("MainActivity", "getAppLinking:onFailure", e);
                });
    }

    // 匿名登录
    public void login() {
        AGConnectAuth auth = AGConnectAuth.getInstance();
        auth.signInAnonymously().addOnSuccessListener(signInResult -> {
            Log.i(TAG, "Sign in for agc success ");
        }).addOnFailureListener(e -> {
            Log.w(TAG, "Sign in for agc failed: " + e.getMessage());
        });
    }

    // 远程配置设置主题
    private void setTheme() {
        SharedPreferences preferences = this.getApplicationContext().getSharedPreferences("Remote_Config", MODE_PRIVATE);
        // 获取数据的间隔时间，单位是秒
        long fetchInterval = 12 * 60 * 60L;
        if (preferences.getBoolean("DATA_OLD", false)) {
            fetchInterval = 0;
        }
        // 使用AGConnectConfig.fetch接口获取远程配置参数值，并为方法添加addOnSuccessListener监听器
        config.fetch(fetchInterval).addOnSuccessListener(configValues -> {
            // Make the configuration parameters take effect
            config.apply(configValues);

            //以String方式获取参数值
            String value = config.getValueAsString("theme_color");
            Log.i("theme_color", "" + value);

            if (value.equals(flag)) {
                // 加载云存储上的图片
                Picasso.with(MainActivity.this)
                        .load("https://agc-storage-drcn.platform.dbankcloud.cn/v0/520-ee2ry/image_detail_background_change.jpeg?token=591703b4-145e-4bf9-a3d2-f67a1006cb59")
                        .networkPolicy(NetworkPolicy.NO_CACHE)
                        .memoryPolicy(MemoryPolicy.NO_CACHE)
                        .into(img_banner);
            }
        }).addOnFailureListener(e -> {
            Toast.makeText(getBaseContext(), "Fetch Fail", Toast.LENGTH_SHORT).show();
        });
        Log.i("MessageDisplay", "display message success");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_add:
                initPopWindow(img_add);
                break;
            case R.id.img_share:
                shareLink(App_LinkingUrl);
                break;
            case R.id.img_banner:
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.addCategory(Intent.CATEGORY_BROWSABLE);
                intent.setData(Uri.parse(App_LinkingUrl));
                startActivity(intent);
                break;
        }
    }

    /**
     * 调用startActivityForResult方法启动一个intent后，
     * 可以在该方法中拿到返回的数据
     * 展示图片
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            // 获取图库所选图片的uri
            Uri uri = data.getData();
            uploadFile(uri2File(uri));
        }
    }

    // uri转file
    private File uri2File(Uri uri) {
        String img_path;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
        if (actualimagecursor == null) {
            img_path = uri.getPath();
        } else {
            int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            actualimagecursor.moveToFirst();
            img_path = actualimagecursor.getString(actual_image_column_index);
        }
        File file = new File(img_path);
        return file;
    }

    // 分享链接
    private void shareLink(String LinkingUrl) {
        if (LinkingUrl != null) {
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT, "好物分享" + LinkingUrl);
            startActivity(intent);
        }
    }

    private void initAGCStorageManagement() {
        mAGCStorageManagement = AGCStorageManagement.getInstance();
        Log.i(TAG, "initAGCStorageManagement success! ");
    }

    // 上传图片至云存储
    private void uploadFile(File file) {
        final String path = "photo.jpg";
        if (!file.exists()) {
            Log.w(TAG, "file is not exist! ");
            return;
        }
        if (mAGCStorageManagement == null) {
            initAGCStorageManagement();
        }
        StorageReference storageReference = mAGCStorageManagement.getStorageReference(path);
        UploadTask uploadTask = (UploadTask) storageReference.putFile(file)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.UploadResult>() {
                    @Override
                    public void onSuccess(UploadTask.UploadResult uploadResult) {
                        Toast.makeText(getBaseContext(), "上传成功! ", Toast.LENGTH_SHORT).show();
                        getDownLoadUrl();
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(Exception e) {
                        Toast.makeText(getBaseContext(), "上传失败 " + e.getMessage(), Toast.LENGTH_LONG).show();
                        Log.w(TAG, "upload failure! " + e.getMessage());
                    }
                });
    }

    // 获取上传图片的链接
    public void getDownLoadUrl() {
        if (mAGCStorageManagement == null) {
            initAGCStorageManagement();
        }
        StorageReference storageReference = mAGCStorageManagement.getStorageReference("photo.jpg");
        Task<Uri> task = storageReference.getDownloadUrl();
        task.addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                String downloadUrl = uri.toString();
                Intent intent = new Intent(MainActivity.this, PhotoActivity.class);
                intent.putExtra("Url", downloadUrl);
                startActivity(intent);
            }
        });
        task.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                Log.e(TAG, "get download url failed: " + e.getMessage());
            }
        });
    }

    // 初始化弹出框
    private void initPopWindow(View v) {
        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.pop_window_device, null, false);
        TextView tv_upload = view.findViewById(R.id.tv_upload);
        //1.构造一个PopupWindow，参数依次是加载的View，宽高
        final PopupWindow popWindow = new PopupWindow(view,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        popWindow.setAnimationStyle(R.style.pop_add);  //设置加载动画

        //这些为了点击非PopupWindow区域，PopupWindow会消失的，如果没有下面的
        //代码的话，你会发现，当你把PopupWindow显示出来了，无论你按多少次后退键
        //PopupWindow并不会关闭，而且退不出程序，加上下述代码可以解决这个问题
        popWindow.setTouchable(true);
        popWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });
        popWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));    //要为popWindow设置一个背景才有效


        //设置popupWindow显示的位置，参数依次是参照View，x轴的偏移量，y轴的偏移量
        popWindow.showAsDropDown(v, 50, 10);

        //设置popupWindow里的按钮的事件
        tv_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 打开手机本地图库选择图片
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, LOCAL_CROP);
                popWindow.dismiss();
            }
        });
    }
}